package com.ishow.bs.servlet;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.ishow.common.constant.SysConfig;


/**
 * Servlet implementation class Log4jLoader
 */

public class ConfigLoader extends HttpServlet {
	private static Logger log = Logger.getLogger(ConfigLoader.class);
	private static final long serialVersionUID = 1L;
	private static final String CONTENT_TYPE = "text/html; charset=UTF-8";

	@Override
	public void destroy() {

	}

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ConfigLoader() {
		super();
	}

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	@Override
	public void init(ServletConfig config) throws ServletException {
		try {
			super.init(config);
			// 在serlvet里使用spring的注入
			WebApplicationContext webApplicationContext = WebApplicationContextUtils
					.getWebApplicationContext(config.getServletContext());

			// 读取配置文件信息
			String file = config.getInitParameter("resource");
			InputStream is = getServletContext().getResourceAsStream(file);
			Properties props = new Properties();
			props.load(is);

			SysConfig.getInstance().setUploadDirectory(
					new String(props.getProperty("UploadDirectory").getBytes("ISO8859-1"), "UTF-8"));
			SysConfig.getInstance().setUploadFilesExtension(
					new String(props.getProperty("UploadFilesExtension").getBytes("ISO8859-1"), "UTF-8"));
			SysConfig.getInstance()
					.setUploadFilesUrl(new String(props.getProperty("UploadFilesUrl").getBytes("ISO8859-1"), "UTF-8"));

			log.info("AppConfig has Loaded......");

			// 检查上传文件目录是否存在，不存在就创建
			File fileDirectory = new File(SysConfig.getInstance().getUploadDirectory());
			if (!fileDirectory.exists()) {
				fileDirectory.mkdirs();
				log.debug("上传文件目录创建成功。目的地址：" + SysConfig.getInstance().getUploadDirectory());
			} else {
				log.debug("上传文件目录已存在。目的地址：" + SysConfig.getInstance().getUploadDirectory());
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			log.error("AppConfig load error......");
		}
	}

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType(CONTENT_TYPE);
	}

}
